<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>C语言中输入输出所有格式控制符 | Tom's develop Blog</title><meta name="keywords" content="printf scanf 输入输出 C语言 格式控制"><meta name="author" content="Tom"><meta name="copyright" content="Tom"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="description" content="C语言输入输出的所有格式控制详解">
<meta property="og:type" content="article">
<meta property="og:title" content="C语言中输入输出所有格式控制符">
<meta property="og:url" content="https://tomsworkspace.github.io/2020/01/16/C%E8%AF%AD%E8%A8%80%E4%B8%AD%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%89%80%E6%9C%89%E6%A0%BC%E5%BC%8F%E6%8E%A7%E5%88%B6%E7%AC%A6/index.html">
<meta property="og:site_name" content="Tom&#39;s develop Blog">
<meta property="og:description" content="C语言输入输出的所有格式控制详解">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper/C语言中输入输出所有格式控制符/figure1.jpg">
<meta property="article:published_time" content="2020-01-16T09:02:06.000Z">
<meta property="article:modified_time" content="2021-02-27T12:13:49.185Z">
<meta property="article:author" content="Tom">
<meta property="article:tag" content="printf scanf 输入输出 C语言 格式控制">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper/C语言中输入输出所有格式控制符/figure1.jpg"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/avatar.png"><link rel="canonical" href="https://tomsworkspace.github.io/2020/01/16/C%E8%AF%AD%E8%A8%80%E4%B8%AD%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%89%80%E6%9C%89%E6%A0%BC%E5%BC%8F%E6%8E%A7%E5%88%B6%E7%AC%A6/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="preconnect" href="//zz.bdstatic.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Tom","link":"链接: ","source":"来源: Tom's develop Blog","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  ClickShowText: {"text":"富强,民主,文明,和谐,自由,平等,公正,法治,爱国,敬业,诚信,友善","fontSize":"15px"},
  lightbox: 'mediumZoom',
  Snackbar: undefined,
  justifiedGallery: {
    js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
    css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
};

var saveToLocal = {
  set: function setWithExpiry(key, value, ttl) {
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-02-27 20:13:49'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = 'true'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }})()</script><meta name="generator" content="Hexo 5.2.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/avator.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">38</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">73</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">12</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></div></div></div></div><div id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/C语言中输入输出所有格式控制符/figure1.jpg)"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Tom's develop Blog</a></span><span id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></div></div><span class="close" id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></span></span></nav><div id="post-info"><h1 class="post-title">C语言中输入输出所有格式控制符</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-01-16T09:02:06.000Z" title="发表于 2020-01-16 17:02:06">2020-01-16</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-02-27T12:13:49.185Z" title="更新于 2021-02-27 20:13:49">2021-02-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/C-C/">C/C++</a></span></div><div class="meta-secondline"> <span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2020/01/16/C%E8%AF%AD%E8%A8%80%E4%B8%AD%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%89%80%E6%9C%89%E6%A0%BC%E5%BC%8F%E6%8E%A7%E5%88%B6%E7%AC%A6/#post-comment"><span class="gitalk-comment-count comment-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="C语言中输入输出所有格式控制符"><a href="#C语言中输入输出所有格式控制符" class="headerlink" title="C语言中输入输出所有格式控制符"></a>C语言中输入输出所有格式控制符</h1><p>&emsp;最近在重温C语言，发现C语言的输入输出函数scanf和printf函数在控制输入输出时有许多控制符来控制输入输出数据的格式。于是就打算来整理一下。</p>
<p>参考<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/printf/7467706?fr=aladdin">百度百科</a>词条</p>
<p>&emsp;scanf()是C语言中的一个输入函数。与printf函数一样，都被声明在头文件stdio.h里。它是格式输入函数，即按用户指定的格式从键盘上把数据输入到指定的变量之中。</p>
<p>&emsp;printf命令的作用是格式化输出函数，一般用于向标准输出设备按规定格式输出信息。printf()函数的调用格式为：printf（”&lt;格式化字符串&gt;”, &lt;参量表&gt;）。printf()是C语言标准库函数，在 stdio.h 中定义。输出的字符串除了可以使用字母、数字、空格和一些数字符号以外，还可以使用一些转义字符表示特殊的含义。</p>
<h2 id="函数定义"><a href="#函数定义" class="headerlink" title="函数定义"></a>函数定义</h2><p>&emsp;int printf(char *format…);<br>&emsp;int scanf(const char * restrict format,…);</p>
<h3 id="函数返回值"><a href="#函数返回值" class="headerlink" title="函数返回值"></a>函数返回值</h3><p>&emsp;printf 函数的返回值为printf实际控制输出的字符数。<br>&emsp;scanf函数返回成功读入的数据项数，读入数据时遇到了“文件结束”则返回EOF。</p>
<h3 id="格式控制字符串format"><a href="#格式控制字符串format" class="headerlink" title="格式控制字符串format"></a>格式控制字符串format</h3><p>&emsp;printf的格式控制字符串format组成如下：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">%[flags][width][.prec][length]type</span><br></pre></td></tr></table></figure>

<p>&emsp;即：%[标志][最小宽度][.精度][类型长度]类型控制符<br>&emsp;详解见下文。</p>
<h2 id="用法详解"><a href="#用法详解" class="headerlink" title="用法详解"></a>用法详解</h2><p>&emsp;通常意义上format的格式如下：[]里的内容表示可选，即可带可不带。</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">%[flags][width][.prec][length]type</span><br></pre></td></tr></table></figure>

<p>&emsp;规定输出数据的格式，具体如下：[1] </p>
<h3 id="类型控制符type"><a href="#类型控制符type" class="headerlink" title="类型控制符type"></a>类型控制符type</h3><p>&emsp;type的字符用于规定输出数据的类型，含义如下：</p>
<table>
<thead>
<tr>
<th align="center">字符</th>
<th align="center">对应数据类型</th>
<th align="left">含义</th>
</tr>
</thead>
<tbody><tr>
<td align="center">d / i</td>
<td align="center">int</td>
<td align="left">接受整数值并将它表示为有符号的十进制整数，i是老式写法</td>
</tr>
<tr>
<td align="center">o</td>
<td align="center">unsigned int</td>
<td align="left">无符号8进制整数(不输出前缀0）</td>
</tr>
<tr>
<td align="center">u</td>
<td align="center">unsigned int</td>
<td align="left">无符号10进制整数</td>
</tr>
<tr>
<td align="center">x / X</td>
<td align="center">unsigned int</td>
<td align="left">无符号16进制整数，x对应的是abcdef，X对应的是ABCDEF（不输出前缀0x)</td>
</tr>
<tr>
<td align="center">f(lf)</td>
<td align="center">double</td>
<td align="left">单精度浮点数和双精度浮点数用f(lf 在C99开始加入标准，意思和 f 相同)</td>
</tr>
<tr>
<td align="center">e / E</td>
<td align="center">double</td>
<td align="left">科学计数法表示的数，基数为10，此处”e”的大小写代表在输出时用的”e”的大小写</td>
</tr>
<tr>
<td align="center">a /A</td>
<td align="center">double</td>
<td align="left">16进制科学计数法表示的数，基数为2,以p表示,以16进制输出，此处”a”的大小写代表在输出时用的”p”的大小写</td>
</tr>
<tr>
<td align="center">g / G</td>
<td align="center">double</td>
<td align="left">有效位数，如：%.8g表示单精度浮点数保留8位有效数字</td>
</tr>
<tr>
<td align="center">c</td>
<td align="center">char</td>
<td align="left">字符型。可以把输入的数字按照ASCII码相应转换为对应的字符</td>
</tr>
<tr>
<td align="center">s / S</td>
<td align="center">char * / wchar_t *</td>
<td align="left">字符串。输出字符串中的字符直至字符串中的空字符（字符串以’\0’结尾，这个’\0’即空字符）</td>
</tr>
<tr>
<td align="center">p</td>
<td align="center">void *</td>
<td align="left">以16进制形式输出指针</td>
</tr>
<tr>
<td align="center">n</td>
<td align="center">int *</td>
<td align="left">到此字符之前为止，一共输出的字符个数，不输出文本</td>
</tr>
<tr>
<td align="center">%</td>
<td align="center">无输入</td>
<td align="left">不进行转换，输出字符‘%’（百分号）本身</td>
</tr>
<tr>
<td align="center">m</td>
<td align="center">无</td>
<td align="left">打印errno值对应的出错内容,(例: printf(“%m\n”); )</td>
</tr>
</tbody></table>
<p>&emsp;注：%g、%G在小数点位数四位或指数大于等于精度时用%e、%E，否则用%f。</p>
<h3 id="标志flags"><a href="#标志flags" class="headerlink" title="标志flags"></a>标志flags</h3><p>&emsp;flags规定输出样式，取值和含义如下：</p>
<table>
<thead>
<tr>
<th align="center">字符</th>
<th align="center">字符名称</th>
<th align="left">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">-</td>
<td align="center">减号</td>
<td align="left">左对齐，右边填充空格(默认右对齐)</td>
</tr>
<tr>
<td align="center">+</td>
<td align="center">加号</td>
<td align="left">在数字前增加符号 + 或 -</td>
</tr>
<tr>
<td align="center">0</td>
<td align="center">数字零</td>
<td align="left">将输出的前面补上0，直到占满指定列宽为止（不可以搭配使用”-“）</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">空格</td>
<td align="left">输出值为正时加上空格，为负时加上负号</td>
</tr>
<tr>
<td align="center">#</td>
<td align="center">井号</td>
<td align="left">type是o、x、X时，增加前缀0、0x、0X;type是e、E、f、g、G时，一定使用小数点;type是g、G时，尾部的0保留</td>
</tr>
</tbody></table>
<figure class="highlight c"><table><tr><td class="code"><pre><span class="line">示例：</span><br><span class="line"><span class="built_in">printf</span>(<span class="string">&quot;%5d\n&quot;</span>,<span class="number">1000</span>);           <span class="comment">//默认右对齐,左边补空格</span></span><br><span class="line"><span class="built_in">printf</span>(<span class="string">&quot;%-5d\n&quot;</span>,<span class="number">1000</span>);              <span class="comment">//左对齐,右边补空格</span></span><br><span class="line"><span class="built_in">printf</span>(<span class="string">&quot;%+d %+d\n&quot;</span>,<span class="number">1000</span>,<span class="number">-1000</span>);     <span class="comment">//输出正负号</span></span><br><span class="line"><span class="built_in">printf</span>(<span class="string">&quot;% d % d\n&quot;</span>,<span class="number">1000</span>,<span class="number">-1000</span>);<span class="comment">//正号用空格替代，负号输出</span></span><br><span class="line"><span class="built_in">printf</span>(<span class="string">&quot;%x %#x\n&quot;</span>,<span class="number">1000</span>,<span class="number">1000</span>);       <span class="comment">//输出0x</span></span><br><span class="line"><span class="built_in">printf</span>(<span class="string">&quot;%.0f %#.0f\n&quot;</span>,<span class="number">1000.0</span>,<span class="number">1000.0</span>)<span class="comment">//当小数点后不输出值时依然输出小数点</span></span><br><span class="line"><span class="built_in">printf</span>(<span class="string">&quot;%g %#g\n&quot;</span>,<span class="number">1000.0</span>,<span class="number">1000.0</span>);   <span class="comment">//保留小数点后后的0</span></span><br><span class="line"><span class="built_in">printf</span>(<span class="string">&quot;%05d\n&quot;</span>,<span class="number">1000</span>);              <span class="comment">//前面补0</span></span><br></pre></td></tr></table></figure>

<h3 id="输出最小宽度width"><a href="#输出最小宽度width" class="headerlink" title="输出最小宽度width"></a>输出最小宽度width</h3><p>&emsp;用于控制显示数值的宽度，取值和含义如下：</p>
<p>&emsp;n(n=1,2,3,4,5,6…)： 宽度至少为n位，不够以空格填充。</p>
<p>&esmp;* 格式列表中，下一个参数还是width</p>
<p>&emsp;width是一个可选的指定最小值字段宽度的十进制数字字符串。如果转换值字符少于字段宽度，该字段将从左到右按指定的字段宽度填充。如果指定了左边调整选项，字段将在右边填充。如果转换结果宽于字段宽度，将扩展该字段以包含转换后的结果。不会发生截断。然而，小的精度可能导致在右边发生截断。</p>
<h3 id="精度-prec"><a href="#精度-prec" class="headerlink" title="精度.prec"></a>精度.prec</h3><p>&emsp;用于控制小数点后面的位数，取值和含义如下：</p>
<p>&emsp;无按缺省精度显示0<br>&emsp;当type=d,i,o,u,x时，没有影响；<br>&emsp;type=e,E,f时，不显示小数点<br>&emsp;n(n=1,2,3…)<br>&emsp;当type=e,E,f时表示的最大小数位数；<br>&emsp;type=其他，表示显示的最大宽度<br>&emsp;prec是指可选的精度。精度是一个.(点)后跟十进制数字字符串。如果没有给出精度，按 0（零）对待。精度指定：</p>
<ul>
<li>* d、o、i、 u、x 或 X 转换的最少数字显示位数。</li>
<li>* e 和 f 转换的基数字符后的最少数字显示位数。</li>
<li>* g 转换的最大有效数字位数。</li>
<li>* s 转换中字符串的最大打印字节数目。</li>
</ul>
<h3 id="类型长度length"><a href="#类型长度length" class="headerlink" title="类型长度length"></a>类型长度length</h3><p>&emsp;类型长度指明待输出数据的长度。因为相同类型可以有不同的长度，比如整型有16bits的short int，32bits的int，也有64bits的long int，浮点型有32bits的单精度float和64bits的双精度double。为了指明同一类型的不同长度，类型长度（length）应运而生，成为格式控制字符串的一部分。</p>
<table>
<thead>
<tr>
<th align="center">length</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">h</td>
<td align="left">参数被解释为短整型或无符号短整型（仅适用于整数说明符：i、d、o、u、x 和 X）。</td>
</tr>
<tr>
<td align="center">l</td>
<td align="left">参数被解释为长整型或无符号长整型，适用于整数说明符（i、d、o、u、x 和 X）及说明符 c（表示一个宽字符）和 s（表示宽字符字符串）。</td>
</tr>
<tr>
<td align="center">L</td>
<td align="left">参数被解释为长双精度型（仅适用于浮点数说明符：e、E、f、g 和 G）。</td>
</tr>
</tbody></table>
<p>&emsp;根据不同的 format 字符串，函数可能需要一系列的附加参数，每个参数包含了一个要被插入的值，替换了 format 参数中指定的每个 % 标签。参数的个数应与 % 标签的个数相同。 [2] </p>
<h3 id="转义序列"><a href="#转义序列" class="headerlink" title="转义序列"></a>转义序列</h3><p>&emsp;这些转义序列在字符串中会被自动转换为相应操作命令。使用的常见转义字符如下：</p>
<table>
<thead>
<tr>
<th align="center">符号</th>
<th align="left">意义</th>
<th align="center">符号</th>
<th align="left">意义</th>
</tr>
</thead>
<tbody><tr>
<td align="center">\a</td>
<td align="left">铃声(提醒)</td>
<td align="center">\b</td>
<td align="left">Backspace</td>
</tr>
<tr>
<td align="center">\f</td>
<td align="left">换页</td>
<td align="center">\n</td>
<td align="left">换行</td>
</tr>
<tr>
<td align="center">\r</td>
<td align="left">回车</td>
<td align="center">\t</td>
<td align="left">水平制表符</td>
</tr>
<tr>
<td align="center">\v</td>
<td align="left">垂直制表符</td>
<td align="center">\’</td>
<td align="left">单引号</td>
</tr>
<tr>
<td align="center">\”</td>
<td align="left">双引号</td>
<td align="center">\\</td>
<td align="left">反斜杠</td>
</tr>
<tr>
<td align="center">?</td>
<td align="left">文本问号</td>
<td align="center">\ooo(例如\024)</td>
<td align="left">ASCII字符(OCX)</td>
</tr>
<tr>
<td align="center">\xhh (例如:\x20)</td>
<td align="left">ASCII字符(HEX)</td>
<td align="center">\xhhhh</td>
<td align="left">宽字符(2字节HEX)</td>
</tr>
</tbody></table>
<p>&emsp;例如，WCHAR f = L’\x4e00’ 或 WCHAR b[] = L”The Chinese character for one is \x4e00”。</p>
<p>[1]Brian W.Kernighan,Dennis M.Ritchie．C程序设计语言．中国：机械工业出版社，2004年1月1日：221-222<br>[2]Stephen Prata．C Primer Plus（第五版）:人民邮电出版社，2005年2月1日</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Tom</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://tomsworkspace.github.io/2020/01/16/C%E8%AF%AD%E8%A8%80%E4%B8%AD%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%89%80%E6%9C%89%E6%A0%BC%E5%BC%8F%E6%8E%A7%E5%88%B6%E7%AC%A6/">https://tomsworkspace.github.io/2020/01/16/C%E8%AF%AD%E8%A8%80%E4%B8%AD%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%89%80%E6%9C%89%E6%A0%BC%E5%BC%8F%E6%8E%A7%E5%88%B6%E7%AC%A6/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://TOMsworkspace.github.io" target="_blank">Tom's develop Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/printf-scanf-%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA-C%E8%AF%AD%E8%A8%80-%E6%A0%BC%E5%BC%8F%E6%8E%A7%E5%88%B6/">printf scanf 输入输出 C语言 格式控制</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper/C语言中输入输出所有格式控制符/figure1.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏<div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/wp.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/wp.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li></ul></div></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/02/24/C%E8%AF%AD%E8%A8%80%E5%85%B3%E9%94%AE%E5%AD%97%E5%92%8C%E4%BF%9D%E7%95%99%E6%A0%87%E8%AF%86%E7%AC%A6/"><img class="prev-cover" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper/C语言中输入输出所有格式控制符/figure1.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">C语言关键字和保留标识符</div></div></a></div><div class="next-post pull-right"><a href="/2020/01/15/%E4%BD%BF%E7%94%A8%E5%85%8D%E8%B4%B9CDN%E6%9C%8D%E5%8A%A1%E5%8A%A0%E9%80%9FGithub%E5%8D%9A%E5%AE%A2/"><img class="next-cover" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/使用免费CDN服务加速Github博客/figure1.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">使用免费CDN服务加速Github博客</div></div></a></div></nav><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside_content" id="aside_content"><div class="card-widget card-info"><div class="card-content"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/avator.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Tom</div><div class="author-info__description">keep curiously!</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">38</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">73</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">12</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/TOMsworkspace"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/TOMsworkspace" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:cqucscw@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div></div><div class="card-widget card-announcement"><div class="card-content"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="card-content"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#C%E8%AF%AD%E8%A8%80%E4%B8%AD%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA%E6%89%80%E6%9C%89%E6%A0%BC%E5%BC%8F%E6%8E%A7%E5%88%B6%E7%AC%A6"><span class="toc-number">1.</span> <span class="toc-text">C语言中输入输出所有格式控制符</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E5%AE%9A%E4%B9%89"><span class="toc-number">1.1.</span> <span class="toc-text">函数定义</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="toc-number">1.1.1.</span> <span class="toc-text">函数返回值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%BC%E5%BC%8F%E6%8E%A7%E5%88%B6%E5%AD%97%E7%AC%A6%E4%B8%B2format"><span class="toc-number">1.1.2.</span> <span class="toc-text">格式控制字符串format</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%A8%E6%B3%95%E8%AF%A6%E8%A7%A3"><span class="toc-number">1.2.</span> <span class="toc-text">用法详解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B1%BB%E5%9E%8B%E6%8E%A7%E5%88%B6%E7%AC%A6type"><span class="toc-number">1.2.1.</span> <span class="toc-text">类型控制符type</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%87%E5%BF%97flags"><span class="toc-number">1.2.2.</span> <span class="toc-text">标志flags</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BE%93%E5%87%BA%E6%9C%80%E5%B0%8F%E5%AE%BD%E5%BA%A6width"><span class="toc-number">1.2.3.</span> <span class="toc-text">输出最小宽度width</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B2%BE%E5%BA%A6-prec"><span class="toc-number">1.2.4.</span> <span class="toc-text">精度.prec</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B1%BB%E5%9E%8B%E9%95%BF%E5%BA%A6length"><span class="toc-number">1.2.5.</span> <span class="toc-text">类型长度length</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BD%AC%E4%B9%89%E5%BA%8F%E5%88%97"><span class="toc-number">1.2.6.</span> <span class="toc-text">转义序列</span></a></li></ol></li></ol></li></ol></div></div></div><div class="card-widget card-recent-post"><div class="card-content"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/09/27/%E6%B5%81%E4%BD%93%E6%A8%A1%E6%8B%9F%E4%B8%8ESPH%E6%96%B9%E6%B3%95/" title="流体模拟与SPH方法"><img data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/09/27/流体模拟与SPH方法/figure1.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="流体模拟与SPH方法"/></a><div class="content"><a class="title" href="/2021/09/27/%E6%B5%81%E4%BD%93%E6%A8%A1%E6%8B%9F%E4%B8%8ESPH%E6%96%B9%E6%B3%95/" title="流体模拟与SPH方法">流体模拟与SPH方法</a><time datetime="2021-09-27T08:46:17.000Z" title="发表于 2021-09-27 16:46:17">2021-09-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/09/11/%E5%BC%B9%E6%80%A7%E6%9C%89%E9%99%90%E5%85%83%E6%96%B9%E6%B3%95/" title="弹性有限元方法"><img data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/09/11/弹性有限元方法/figure1.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="弹性有限元方法"/></a><div class="content"><a class="title" href="/2021/09/11/%E5%BC%B9%E6%80%A7%E6%9C%89%E9%99%90%E5%85%83%E6%96%B9%E6%B3%95/" title="弹性有限元方法">弹性有限元方法</a><time datetime="2021-09-11T09:05:34.000Z" title="发表于 2021-09-11 17:05:34">2021-09-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/09/%E5%BC%B9%E7%B0%A7%E8%B4%A8%E7%82%B9%E7%B3%BB%E7%BB%9F%E4%B8%8E%E6%97%B6%E9%97%B4%E7%A7%AF%E5%88%86/" title="弹簧质点系统与时间积分"><img data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/08/09/弹簧质点系统与时间积分/figure1.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="弹簧质点系统与时间积分"/></a><div class="content"><a class="title" href="/2021/08/09/%E5%BC%B9%E7%B0%A7%E8%B4%A8%E7%82%B9%E7%B3%BB%E7%BB%9F%E4%B8%8E%E6%97%B6%E9%97%B4%E7%A7%AF%E5%88%86/" title="弹簧质点系统与时间积分">弹簧质点系统与时间积分</a><time datetime="2021-08-09T13:39:12.000Z" title="发表于 2021-08-09 21:39:12">2021-08-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/08/OpenGL%E5%9D%90%E6%A0%87%E7%B3%BB%E7%BB%9F/" title="OpenGL坐标系统"><img data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/08/08/OpenGL坐标系统/figure1.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="OpenGL坐标系统"/></a><div class="content"><a class="title" href="/2021/08/08/OpenGL%E5%9D%90%E6%A0%87%E7%B3%BB%E7%BB%9F/" title="OpenGL坐标系统">OpenGL坐标系统</a><time datetime="2021-08-08T12:57:28.000Z" title="发表于 2021-08-08 20:57:28">2021-08-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/06/Doxygen%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90%E6%96%87%E6%A1%A3/" title="Doxygen自动生成文档"><img data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/08/06/Doxygen自动生成文档/Doxygen.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Doxygen自动生成文档"/></a><div class="content"><a class="title" href="/2021/08/06/Doxygen%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90%E6%96%87%E6%A1%A3/" title="Doxygen自动生成文档">Doxygen自动生成文档</a><time datetime="2021-08-06T13:24:50.000Z" title="发表于 2021-08-06 21:24:50">2021-08-06</time></div></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2021 By Tom</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my <a href="https://TOMsworkspace.github.io/">blog</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module" defer></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    loader: {
      source: {
        '[tex]/amsCd': '[tex]/amscd'
      }
    },
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        addClass: [200,() => {
          document.querySelectorAll('mjx-container:not([display=\'true\']').forEach( node => {
            const target = node.parentNode
            if (!target.classList.contains('has-jax')) {
              target.classList.add('mathjax-overflow')
            }
          })
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex@latest/dist/katex.min.css"><script src="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.css"><script>$(function () {
  $('span.katex-display').wrap('<div class="katex-wrap"></div>')
})</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk({
      clientID: 'e50742231659674c31e3',
      clientSecret: '59038139e289bc384e484d341205bbb95a123209',
      repo: 'TOMsworkspace.github.io',
      owner: 'TOMsworkspace',
      admin: ['TOMsworkspace'],
      id: '6fb40867a32d1fb6da8ee5c4bb6b02e0',
      language: '-zh-CN# en, zh-CN, zh-TW, es-ES, fr, ru',
      perPage: 10,
      distractionFreeMode: false,
      pagerDirection: 'last',
      createIssueManually: true,
      updateCountCallback: commentCount
    })
    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    $.getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js', initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" async="async" mobile="false"></script><script>(function(){
  const bp = document.createElement('script');
  const curProtocol = window.location.protocol.split(':')[0];
  if (curProtocol === 'https'){
  bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
  }
  else{
  bp.src = 'http://push.zhanzhang.baidu.com/push.js';
  }
  bp.dataset.pjax = ''
  const s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(bp, s);
})()</script></div></body></html>